#include <Lucnx/vsprintf.h>
#include <Lucnx/interrupt.h>
#include <Lucnx/system.h>
#include <Lucnx/printk.h>
#include <Lucnx/stdlib.h>
#include <Lucnx/debug.h>
#include <Lucnx/device.h>
#include <Lucnx/ide.h>
#include <Lucnx/io.h>

#define IDE_READ_CMD 0x20   // 读
#define IDE_WRITE_CMD 0x30  // 写

#define IDE_DRQ 0b00001000
#define IDE_ERR 0b00000001
#define IDE_BSY 0b10000000
#define IDE_RDY 0b01000000

static ide_ctrl_t ide_ctrl_table[2];
static int ide_disk_count;
static int ide_ctrl_count;

void ide_init()
{
    ide_disk_count = *((u8 *) 0x475);
    ide_ctrl_count = DIV_ROUND_UP(ide_disk_count, 2);

    for (size_t i = 0; i < ide_ctrl_count; i++)
    {
        ide_ctrl_t *ctrl = ide_ctrl_table + i;

        sprintf(ctrl->name, "ide%d", i + 1);
        ctrl->irq = 0x2E + i;
        ctrl->port = 0x1F0 - i * 0x80;
        ctrl->waiter = NULL;
        device_install(ctrl->name, NULL, NULL, NULL, NULL, DEV_DEFAULT, 0);

        for (size_t nr = 0; nr < ide_disk_count % 2; nr++)
        {
            disk_t *device = ctrl->devices + nr;
            device->ctrl = ctrl;
            device->device_no = nr;
            sprintf(device->name, "sd%c", i * 2 + nr + 'a');
            device_install(device->name, device, NULL, NULL, NULL, DEV_BLK, 0);
        }

        lock_init(&ctrl->lock);
    }
}